package com.goblin.model.media.controller;

import com.goblin.common.response.PageHelper;
import com.goblin.common.response.Paged;
import com.goblin.common.response.Response;
import com.goblin.model.base.BaseController;
import com.goblin.model.media.po.Message;
import com.goblin.model.media.service.MessageService;
import com.goblin.model.socket.SocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/v1/media/chat/message")
public class MessageController extends BaseController<Message> {

    @Autowired
    private MessageService messageService;

    @GetMapping("/messages/{chatId}")
    public Response<Paged<Message>> paged(@PathVariable Integer chatId, PageHelper pageable) {
        Paged<Message> entities = this.messageService.paged(chatId, pageable);
        return Response.success(entities);
    }

    @Override
    public void before(Message po) {
        super.before(po);
        po.setDate(new Date());

        if (po.getReceive() == null) {
            try {
                SocketServer.sendMessage(po, po.getUserTo().getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else
            po.setReceive(false);

    }

}
